package image

import (
	"context"
	"fmt"
	"github.com/Unixeno/islands/cmd/connection"
	"github.com/Unixeno/islands/cmd/utils"
	"github.com/Unixeno/islands/pb"
	"github.com/spf13/cobra"
)

var importMethod string

func GetImageImportCmd() *cobra.Command {
	imageImportCmd := &cobra.Command{
		Use:   "import [OPTIONS] path [name]",
		Short: "import your image",
		Long:  `import the image into your repo by "raw" or "docker"`,
		Args:  cobra.MinimumNArgs(1),
		Run:   importHandle,
	}
	imageImportCmd.Flags().StringVar(&importMethod, "type", "docker", `method to import your image, support "docker" and "raw"`)
	return imageImportCmd
}

func importHandle(cmd *cobra.Command, args []string) {
	// 检查路径是否存在
	if len(args) < 1 {
		_ = cmd.Help()
		return
	}

	if !utils.PathExist(args[0]) {
		fmt.Println("path doesn't exit")
		return
	}

	path := args[0]
	name := ""

	if len(args) == 2 {
		name = args[1]
	}

	var r *pb.ImportImageResp
	var err error

	switch importMethod {
	case "raw":
		r, err = connection.Client.ImportRawImage(context.Background(), &pb.ImportRawImageReq{
			Path: path,
			Name: name,
		})
	case "docker":
		r, err = connection.Client.ImportDockerImage(context.Background(), &pb.ImportDockerImageReq{
			Path: path,
			Name: name,
		})
	default:
		fmt.Println("unknown type of image")
		return
	}

	if err != nil {
		fmt.Printf("Cannot import for reason %v\n", err)
	} else {
		if !utils.PrintError(r.Err) {
			fmt.Println(r.Id)
		}
	}
}
